﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Sgr.Data;
using Sgr.EntityFrameworkCore.EntityConfigurations;
using Sgr.UPMS.Domain.Departments;

namespace Sgr.UPMS.Infrastructure.EntityConfigurations
{
    internal class DepartmentEntityTypeConfiguration : EntityTypeConfigurationBase<Department, long>
    {
        public DepartmentEntityTypeConfiguration(DatabaseType? databaseType = null) : base(databaseType)
        { }

        public override void Configure(EntityTypeBuilder<Department> builder)
        {
            builder.ToTable("upms_department");

            base.Configure(builder);

            builder.PropertyAndHasColumnName(b => b.Code, GetColumnNameCase())
                .HasMaxLength(200)
                .IsRequired()
                .HasComment("部门编码");

            builder.PropertyAndHasColumnName(b => b.Name, GetColumnNameCase())
                .HasMaxLength(200)
                .IsRequired()
                .HasComment("部门名称");

            builder.PropertyAndHasColumnName(b => b.OrderNumber, GetColumnNameCase())
                .IsRequired()
                .HasComment("组织排序号");

            builder.PropertyAndHasColumnName(b => b.ManagerUserId, GetColumnNameCase())
                .HasComment("主管用户Id");

            builder.PropertyAndHasColumnName(b => b.Leader, GetColumnNameCase())
                .HasMaxLength(50)
                .HasComment("负责人(冗余)");

            builder.PropertyAndHasColumnName(b => b.Phone, GetColumnNameCase())
                .HasMaxLength(50)
                .HasComment("联系电话(冗余)");

            builder.PropertyAndHasColumnName(b => b.Email, GetColumnNameCase())
                .HasMaxLength(50)
                .HasComment("联系邮箱(冗余)");

            builder.PropertyAndHasColumnName(b => b.State, GetColumnNameCase())
                .IsRequired()
                .HasComment("部门状态");

            builder.PropertyAndHasColumnName(b => b.Remarks, GetColumnNameCase())
                .HasMaxLength(500)
                .HasComment("描述");

            //索引
            base.AddOrgIndex(builder);

            // 针对部门ID和名称的联合索引（优化查询性能）
            builder.HasIndex(b => new { b.Id, b.Name })
                .HasDatabaseName("IX_Department_Id_Name")
                .IsUnique(false);  // 不需要唯一约束，因为是为了优化查询
            //builder.HasIndex(b => b.Code);
        }
    }
}